package com.thundersoft.musicbox;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.thundersoft.musicbox.model.Music;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 备注:
 *
 * @author hmb
 * @version 1.0
 * @since 2015/11/19 13:05
 */
public class MusicManager {
    private MediaPlayer player = null;

    private boolean isPause = false;

    private int currentPosition = 0;

    private Context mContext;

    public MusicManager(MediaPlayer mediaPlayer) {
        player = mediaPlayer;
        player.setLooping(false);
        mContext = MusicApplication.getContext();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(mContext, "播放完成", Toast.LENGTH_SHORT).show();
                next();
            }
        });

    }




    /**
     * 播放
     */
    public void play() {

        if (isPause) {//暂停状态，继续播放
            player.start();
            isPause = false;
            return;
        }
        List<Music> list = MusicContext.getMusicList();
        if (MusicContext.getMusicList().isEmpty()) {
            Toast.makeText(mContext, "没有文件", Toast.LENGTH_SHORT).show();
            return;
        }
        player.reset();

        try {
            player.setDataSource(list.get(currentPosition).getPath());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 暂停
     */
    public void pause() {
        player.pause();
        isPause = true;
    }

    /**
     * 上一首
     */
    public void last() {
        if (currentPosition == 0) {
            List<Music> list = MusicContext.getMusicList();
            if (!list.isEmpty()) {

                currentPosition = list.size() - 1;
                play();
            }
        } else {
            currentPosition--;
            play();
        }
    }

    /**
     * 下一首
     */
    public void next() {
        List<Music> list = MusicContext.getMusicList();
        if (currentPosition < list.size() - 1) {
            currentPosition++;
        } else {
            currentPosition = 0;
        }
        play();
    }

    public void playOrPause() {
        if (player.isPlaying()) {
            this.pause();
        } else {
            this.play();
        }
    }

    /**
     * 停止
     */
    public void stop() {
        player.stop();
    }

    public Music getCurrentMusic() {
        List<Music> list = MusicContext.getMusicList();
        if (currentPosition >= list.size()) {
            return null;
        }
        return list.get(currentPosition);
    }

    public boolean isPlaying(){
        return player.isPlaying();
    }
}
